<template>
  <div>
    <!--面包屑组件-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片组件-->
    <el-card>
      <!--栅格组件-->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table stripe border :data="rolesList">
        <!--展开列-->
        <!--type="expand"则该列可展开，展开的视图在该行的下方-->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="[
                'bestRolesBorderBottom',
                index === 0 ? 'bestRolesBorderTop' : '',
                'vcenter'
              ]"
            >
              <!--第一列渲染一级权限-->
              <el-col :span="5" class="col-center">
                <el-tag
                  @close="rolesTagDelete(scope.row, item.id)"
                  type=""
                  closable
                  >{{ item.authName }} </el-tag
                ><i class="el-icon-caret-right"></i>
              </el-col>
              <!--第二列渲染二级和三级权限-->
              <el-col :span="19">
                <el-row
                  v-for="(childItem, index) in item.children"
                  :key="childItem.id"
                  :class="[index !== 0 ? 'bestRolesBorderTop' : '', 'vcenter']"
                >
                  <el-col :span="6" class="col-center">
                    <el-tag
                      closable
                      type="success"
                      @close="rolesTagDelete(scope.row, childItem.id)"
                    >
                      {{ childItem.authName }} </el-tag
                    ><i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="sunItem in childItem.children"
                      :key="sunItem.id"
                      closable
                      @close="rolesTagDelete(scope.row, sunItem.id)"
                      >{{ sunItem.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="290px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="getEditRolesForm(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteRoles"
              >删除</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="getSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :visible.sync="setRightDialog"
      title="分配权限"
      width="50%"
      @close="rightsDialogClose"
    >
      <el-tree
        ref="setRightsTreeRef"
        :data="rightList"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
        :default-checked-keys="defKeys"
      >
      </el-tree>
      <span slot="footer">
        <el-button type="primary" @click="setRightDialogImpower"
          >确 定</el-button
        >
        <el-button @click="setRightDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="editRoleDialog" title="编辑角色">
      <el-form :model="editRoleForm" label-width="80px" :rules="editRoleRules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="editRole">修 改</el-button>
        <el-button @click="editRoleDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "roles",
  data() {
    return {
      rolesList: [],
      setRightDialog: false,
      rightList: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      defKeys: [],
      rolesId: "",
      editRoleDialog: false,
      editRoleForm: {},
      editRoleRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur"
          },
          {
            min: 3,
            max: 10,
            message: "角色名长度应在3到10个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败，请重试!");
      this.rolesList = res.data;
    },
    //  获取编辑角色表单
    getEditRolesForm(role) {
      this.editRoleForm = role;
      this.editRoleDialog = true;
    },
    //  删除角色
    deleteRoles() {},
    // 获取分配权限对话框
    //  当一个函数中有网络请求操作时，不要单独将请求操作封装后再调用，这样无法保证是在网络请求操作结束后再执行后面的操作
    async getSetRightDialog(roles) {
      this.rolesId = roles.id;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败，请重试!");
      this.rightList = res.data;
      this.getDefKeys(roles, this.defKeys);
      this.setRightDialog = true;
      // this.$nextTick(() => {
      //   if (this.$refs.setRightsTreeRef) {
      //     this.$refs.setRightsTreeRef.setCheckedKeys(this.defKeys);
      //   }
      // });
    },
    //  获取tree组件默认选中的项的key
    getDefKeys(rightObj, keys) {
      if (!rightObj.children) {
        return keys.push(rightObj.id);
      }
      rightObj.children.forEach((item) => {
        this.getDefKeys(item, keys);
      });
    },
    rightsDialogClose() {
      this.defKeys = [];
    },
    async setRightDialogImpower() {
      const { data: res } = await this.$http.post(
        `roles/${this.rolesId}/rights`,
        {
          rids: [
            ...this.$refs.setRightsTreeRef.getCheckedKeys(),
            ...this.$refs.setRightsTreeRef.getHalfCheckedKeys()
          ].join(",")
        }
      );
      if (res.meta.status !== 200) {
        console.log(res);
        return this.$message.error("授权失败,请重试!");
      }
      this.getRolesList();
      this.$message.success("授权成功!");
      this.setRightDialog = false;
    },
    //  删除权限事件
    rolesTagDelete(role, rightId) {
      this.$confirm("此操作将删除该权限, 是否继续?", "删除权限", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("权限删除失败，请重试！");
          }
          role.children = res.data;
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async editRole() {
      const { data: res } = await this.$http.put(
        `roles/${this.editRoleForm.id}`,
        {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("修改角色失败，请重试!");
      }
      this.getRolesList();
      this.editRoleDialog = false;
      this.$message.success("修改角色成功!");
    }
  }
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}

.el-tag {
  margin: 7px;
}

.bestRolesBorderTop {
  border-top: 1px solid #eee;
}
.bestRolesBorderBottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
.col-center {
  text-align: center;
}
</style>
